import {NextFunction, Request, Response} from "express";

// 封装一个响应 "通用错误消息" 的中间件
export const errMsg = (req:Request,res:Response, next: NextFunction) => {
  res.gem = (msg: string) => {
    return res.send({ meta: { status: 400,  msg }})
  }
  next()
}

// 封装一个响应 "通用成功消息" 的中间件
export const sucMsg = (req:Request,res:Response, next: NextFunction) => {
  res.gsm = (msg: string) => {
    return res.send({ meta: { status: 200, msg }})
  }
  next()
}

// 封装一个响应 "通用登录成功消息数据 (登录成功，返回token)" 的中间件
export const sucLoginData = (req:Request, res:Response, next: NextFunction) => {
  res.gsmdt = (userInfo: object, token?: string, msg = '登录成功！') => {
    return res.send({
      meta: { status: 200, msg },
      data: { userInfo, token}
    })
  }
  next()
}

// 封装一个响应 通用成功消息数据 的中间件
export const sucData = (req:Request, res: Response, next: NextFunction) => {
  res.gsmd = (data: any , msg = '查询成功！') => {
    return res.send({
      meta: { status: 200, msg },
      data: { data }
    })
  }
  next()
}

// 封装一个响应 "通用成功消息数据列表" 的中间件
export const sucDataList = (req:Request,res:Response, next: NextFunction) => {
  res.gsmdl = (total: number, list: [], msg = '查询成功') => {
    return res.send({
      meta: { status: 200, msg },
      data: { total, list}
    })
  }
  next()
}

// 定义捕获错误的中间件
export const catchError = (err:Error, req:Request, res:Response, next:NextFunction) => {
  // token 错误
  if (err.name === 'UnauthorizedError') {
    return res.gem('无效的token，身份认证失败~')
  }
}